
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');
var md = require('../../utils/md5.js');

var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    phone: "",
    pwd: "",
    login_code: "",
    login_encryptedData: "",
    login_iv: "",
    openid: "",
    // sessionkey: ""
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.login_error_code != undefined && options.login_error_code == 11906) {
      this.setData({
        login_error_code: 11906
      })
    } else {
      this.autoLogin()
    }
  },

  onShow: function () {
    var that = this;
    setTimeout(function () {
      if (that.data.login_error_code == '') {
        that.autoLogin()
      } else {
        that.setData({
          login_error_code: ''
        })
      }
    }, 500)
  },

  // 自动登录
  autoLogin: function () {
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          api.POST({
            params: { code: res.code },
            url: app.globalData.login_url,
            success: function (respone) {
              if (util.isEmpty(respone.data.code)) {
                util.hiddenLoading();
                app.globalData.loginState = 1;
                wx.setStorageSync("isLogin", "1");
                var accountInfo = respone.data.data.result;
                app.globalData.accountInfo = accountInfo;
                wx.switchTab({
                  url: '../sales/sales',
                })
              } else {
                wx.removeStorageSync('isLogin');
                app.globalData.loginState = '';
                if (respone.data.code == '11906') {
                  //用户登录信息为空
                } else if (respone.data.code == '5802') {
                  util.showError("密码错误");
                } else if (respone.data.code == '2499') {
                  util.showError("该账号已经绑定过其他微信账号了");
                } else if (respone.data.code == '2400'){
                  util.showError('账号不存在');
                }
              }
            },
            fail: function (fail) {
              // console.log("autoLogin = 登录失败");
            }
          })
        }
      },
      fail: function () {
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  //输入电话
  bindPhoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },

  //输入密码
  bindPwdInput: function (e) {
    this.setData({
      pwd: e.detail.value
    })
  },

  //点击登录按钮
  login_clicked: function (e) {
    var that = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          that.login_weixin()
        }
      }
    })
  },

  //获取code,iv，encryptedData
  login_weixin: function (e) {
    var that = this;
    if (!util.validateMobile(that.data.phone)) { util.showError('请输入正确手机号'); return; }
    if (util.isEmpty(that.data.pwd)) { util.showError('请输入密码'); return; }
    util.showLoading('登录中...');
    wx.login({
      success: function (res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            that.setData({
              login_code: res_login.code,
              login_encryptedData: res_user.encryptedData,
              login_iv: res_user.iv
            });
            that.login_request();
          }, fail: function (fail_res) {
            if (fail_res.errMsg == "getUserInfo:fail auth deny") {
              that.showModal();
            }
          }
        })
      }, fail: function (fail_login) {
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  //请求后台登录
  login_request: function () {
    var that = this;
    var params = new Object()
    params.code = that.data.login_code;
    params.encryptedData = that.data.login_encryptedData;
    params.iv = that.data.login_iv;
    params.mobile = that.data.phone;
    params.password = md(that.data.pwd);
    if (that.data.openid) {
      params.openid = that.data.openid;
      // params.sessionkey = that.data.sessionkey;
    }
    api.POST({
      params: params,
      url: app.globalData.login_url,
      success: function (res) {
        wx.hideLoading()
        if (res.data.code) {
          if (res.data.code == '2499') {
            wx.showModal({
              title: '提示',
              content: '请前往已绑定的微信登录;如需解绑或其他问题请联系客服',
              confirmText: '好',
              cancelText: '联系客服',
              success: function (suress) {
                if (!suress.confirm) {
                  wx.makePhoneCall({
                    phoneNumber: app.globalData.service_phone, //此号码并非真实电话号码，仅用于测试
                  })
                }
              }
            })
          } else if (res.data.code == '5802') {
            util.showError("密码错误");
          } else if (res.data.code == '2400') {
            util.showError('账号不存在');
          } else {
            util.showError(res.data.message);
          }

        } else {
          if (res.data.data.result.openid != undefined || res.data.data.result.openid != '') {
            that.setData({
              openid: res.data.data.result.openid,
              // sessionkey: res.data.data.result.sessionkey
            });
          }
          app.globalData.loginState = 1;
          wx.setStorageSync("isLogin", "1");
          app.globalData.accountInfo = res.data.data.result;
          var accountInfo = app.globalData.accountInfo;
          wx.switchTab({
            url: '../sales/sales',
          })
        }
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  //忘记密码
  forget_password_clicked: function () {
    wx.navigateTo({
      url: '../forgetPassword/forgetPassword',
    })
  },

  // 重新授权
  reAuthorization: function () {
    var that = this
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"]) {
          that.login_weixin();
        }
      }
    })
  },

  showModal: function () {
    var that = this;
    wx.showModal({
      title: '警告',
      content: '若不授权登录，则无法使用',
      confirmText: '授权',
      cancelText: '不授权',
      success: function (suress) {
        if (suress.confirm) {
          that.reAuthorization();
        }
      }
    })
  },
})